//
//  YWFinishDetectAndUpkeepTableViewController.m
//  maintain
//
//  Created by Kyo on 16/9/22.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWFinishDetectAndUpkeepTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "UIScrollView+EmptyDataSet.h"
#import "NSDate+YYAdd.h"
#import "MJExtension.h"
#import "MJRefresh.h"
#import "YWCommonTool.h"
#import "UIView+Extension.h"

#import "YWNotifyManager.h"
#import "YWDetectAndUpkeepManager.h"
#import "YWMissionManager.h"
#import "YWMissionDetailsViewController.h"

#import "YWPush.h"

#import "UITableView+FDTemplateLayoutCell.h"
#import "YWWorkTableViewCell.h"

@interface YWFinishDetectAndUpkeepTableViewController ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>{
    BOOL isLoadData;
    NSUInteger page;
}
@property (nonatomic, strong) NSMutableArray* sourceDatas;
@end

@implementation YWFinishDetectAndUpkeepTableViewController
//- (instancetype)init{
//    return [super initWithStyle:UITableViewStyleGrouped];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor customBackgroudColor];
    isLoadData = NO;
    
    [self setupTableView];
    [self setupNotifications];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (isLoadData==NO) {
        isLoadData = YES;
        page=1;
        _sourceDatas = nil;
        [self.tableView reloadData];
    }
}

- (void)setupTableView{
    [self.tableView registerClass:[YWWorkTableViewCell class] forCellReuseIdentifier:YWWorkTableViewCellIdentifier];
    
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, KbottomViewH, 0);
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.sectionFooterHeight = 0.1;
    
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
}

- (void)setupNotifications{
    [[YWNotifyManager shareManager] addMissionFinishedObserver:self selector:@selector(refreshTableView:)];
    [[YWNotifyManager shareManager] addMissionProgressObserver:self selector:@selector(refreshPushMissionShow:)];
    [[YWNotifyManager shareManager] addAssignDetectMissionObserver:self selector:@selector(refreshTop)];
    [[YWNotifyManager shareManager] addAssignUpKeepMissionObserver:self selector:@selector(refreshTop)];
    [[YWNotifyManager shareManager] addDeleteMissionObserver:self selector:@selector(deleteMission:)];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDetectAndUpkeepMission:) name:KRefreshPostAssignDetectAndUpkeepMissionNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDetectAndUpkeepMission:) name:KRefreshDeleteDetectAndUpkeepMissionNotification object:nil];
}

- (NSArray*)sourceDatas{
    if (!_sourceDatas) {
        _sourceDatas = [NSMutableArray array];
        [_sourceDatas addObjectsFromArray:[YWDetectAndUpkeepManager detectAndUpkeepMissionWithStatus:YWMissionFinishStatusFinishedAndExpire maintenanceType:self.maintenanceType page:page]];
    }
    return _sourceDatas;
}

- (void)refreshTop{
    page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType{
    YWWeakSelf(weakSelf);
    dispatch_group_t group = dispatch_group_create();
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        if (refreshType == YWTableViewFreshTypeUp) {
            page++;
        }
        
        if (_maintenanceType == YWMaintenanceTypeDetection){
            dispatch_group_enter(group);
            [YWDetectAndUpkeepManager requestDetectAndUpKeepMissionWithUrl:[YWCommonTool getDetectionMissionUrl] page:page pageSize:10 status:YWMissionFinishStatusFinishedAndExpire completeBlock:^(NSInteger count) {
                dispatch_group_leave(group);
            }];
        }else if (_maintenanceType == YWMaintenanceTypeUpkeep){
            dispatch_group_enter(group);
            [YWDetectAndUpkeepManager requestDetectAndUpKeepMissionWithUrl:[YWCommonTool getUpkeepMissionUrl] page:page pageSize:10 status:YWMissionFinishStatusFinishedAndExpire completeBlock:^(NSInteger count) {
                dispatch_group_leave(group);
            }];
        }
        
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (refreshType == YWTableViewFreshTypeDown) {
                [weakSelf.tableView.mj_header endRefreshing];
            }
            else {
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            weakSelf.sourceDatas = nil;
            [weakSelf.tableView reloadData];
        });
    });
}

#pragma mark - Table view data source
//- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
//{
//    return [tableView fd_heightForCellWithIdentifier:YWWorkTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWWorkTableViewCell *cell) {
//        [self configureCell:cell atIndexPath:indexPath];
//    }];
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView{
    return [self.sourceDatas count];
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.sourceDatas[section] count];
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
    YWWorkTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWorkTableViewCellIdentifier];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

#pragma mark - configure cell
- (void)configureCell:(YWWorkTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    YWMaintenanceMission* mission = self.sourceDatas[indexPath.section][indexPath.row];
    cell.maintenanceMission = mission;
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

#pragma mark - table view section header view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWFinishDetectAndUpkeepTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor blackColor];
        label.tag = 2016;
        label.font = KTitleFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    NSArray *array = self.sourceDatas[section];
    YWMaintenanceMission* mission = array.count ? array[0] : nil;
    NSTimeInterval timeInterval = mission.createTime / 1000;
//    if (mission.missionStatus == YWMissionStatusFinished) {
//        timeInterval = mission.finishTime / 1000;
//    }else {
//        timeInterval = mission.createTime / 1000;
//    }
    NSString *time = [YWCommonTool showChineseFormatterDate:timeInterval];
    NSInteger weekDay = [NSDate dateWithTimeIntervalSince1970:timeInterval].weekday;
    NSString *weekStr = [YWCommonTool weekDayString:weekDay-1];
    NSString * title = [NSString stringWithFormat:@"%@  %@",time,weekStr];
    return title;
}


- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YWMaintenanceMission* mission = self.sourceDatas[indexPath.section][indexPath.row];
    YWMissionDetailsViewController* missionDetailsVC = [[YWMissionDetailsViewController alloc] init];
    missionDetailsVC.mission = mission;
    [self.navigationController pushViewController:missionDetailsVC animated:YES];
}

#pragma mark - Noti methods

- (void)deleteMission:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWPushCancelMission class]]) {
        YWPushCancelMission* pushMission = noti.object;
        if (pushMission.missionId>0) {
            _sourceDatas = nil;
            [self.tableView reloadData];
        }
    }
}

- (void)refreshTableView:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWMaintenanceMission class]]) {
        _sourceDatas = nil;
        [self.tableView reloadData];
    }
}


- (void)refreshPushMissionShow:(NSNotification*)noti{
    NSDictionary* obj = noti.object;
    NSInteger missionId = [[obj objectForKey:@"missionId"] integerValue];
    __block BOOL needReload = NO;
    if (missionId > 0) {
        NSInteger maintenanceType = [[obj objectForKey:@"maintenanceType"] integerValue];
        NSInteger missionStatus = [[obj objectForKey:@"status"] integerValue];
        [self.sourceDatas enumerateObjectsUsingBlock:^(NSMutableArray*  _Nonnull array, NSUInteger idx, BOOL * _Nonnull arrayStop) {
            [array enumerateObjectsUsingBlock:^(YWMaintenanceMission* _Nonnull mission, NSUInteger idx, BOOL* _Nonnull stop) {
                if (missionId == mission.missionId) {
                    if (maintenanceType != YWMaintenanceTypeTrouble) {
                        NSInteger completedQuantity = [[obj objectForKey:@"completedQuantity"] integerValue];
                        if (completedQuantity > 0 && completedQuantity > mission.completedQuantity) {
                            needReload = YES;
                            mission.completedQuantity = completedQuantity;
                            mission.missionStatus = missionStatus;
                            mission.finishTime = [[NSDate date] timeIntervalSince1970] * 1000;
                            [YWDetectAndUpkeepManager updateDetectAndUpkeepMissionWithArray:@[ mission ]];
                            *stop = YES;
                            *arrayStop = YES;
                        }
                    }
                }
            }];
        }];
        
        if (needReload) {
            [self.tableView reloadData];
        }
    }
}

- (void)refreshDetectAndUpkeepMission:(id)sender{
    _sourceDatas = nil;
    [self.tableView reloadData];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
